﻿// 
//    Copyright 2010 The JaernCloud Project
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JaernCloud.Language.Compiler.Types;
using System.Dynamic;
using JaernCloud.Language.Compiler.Ast;
using JaernCloud.Language.Compiler.Types.Builtin;
using JaernCloud.Language.Runtime.View;

namespace JaernCloud.Language.Runtime {

    /// <summary>
    /// Represents a query node in which a query is expanded and children nodes created based on the query result
    /// </summary>
    public class QueryNodeObject : NodeObject<IQueryNodeType>, IQueryNodeObject, IRenderNodeObject {

        private List<INodeObject<INodeType>> _children;
        private List<INodeObject<INodeType>> _results;

        public override INodeObject<IQueryNodeType> FromType(INodeType nodeType, INodeObjectGenerator objectGenerator) {
            return new QueryNodeObject { _type = (IQueryNodeType)nodeType, _objectGenerator = objectGenerator };
        }

        public INodeObject<INodeType> EvaluateExpression(string propertyName, INodeObject<INodeType> context) {
            // TODO: Make this effective (keep track of current branch somehow when expressions further down the tree are evaluated)
            foreach (var child in Children) {
                if (child.Names.Contains(propertyName)) {
                    var parent = context.Parent;
                    while (parent != null) {
                        if (parent == child) {
                            return child;
                        }
                        parent = parent.Parent;
                    }
                }
            }
            return null;
        }

        public IEnumerable<INodeObject<INodeType>> Results {
            get {
                if (_results == null) {
                    _results = new List<INodeObject<INodeType>>();
                    switch (Type.QueryKind) {
                        case QueryKind.Expression:
                            IExpressionNodeObject expression = (IExpressionNodeObject)_objectGenerator.GetNodeObjectInstanceFor(Type.QueryOperatorType);
                            dynamic results = expression.ExpressionValue;
                            if (results is IEnumerable<object>) {
                                IEnumerable<object> enumerable = (IEnumerable<object>)results;
                                INodeType queryResultType = NodeTypeGenerator.GetNodeTypeInstanceFor(Type.Owner.SourceNode);
                                foreach (object result in enumerable) {                                   
                                    INodeObject<INodeType> resultNode = _objectGenerator.GetNodeQueryResultObjectInstanceFor(queryResultType);
                                    if (resultNode is IQueryResultNodeObject) {
                                        (resultNode as IQueryResultNodeObject).AddValue(result, Type.QueryOperator.Identifier);
                                        resultNode.Parent = this;
                                    } else {
                                        throw new ArgumentException(resultNode + " must be " + typeof(IQueryResultNodeObject) + " to support query results");
                                    }
                                    _results.Add(resultNode);
                                }
                            } else {
                                // single result (if operator for example)
                                throw new NotImplementedException("TODO: Single result");
                            }
                            break;
                        case QueryKind.TagWithId:
                            throw new NotImplementedException();
                            break;
                        case QueryKind.ByExample:
                            throw new NotImplementedException();
                            break;
                        default:
                            throw new NotSupportedException(Type.QueryKind + " is not supported");
                    }
                }
                return _results;
            }
        }

        public override string Name {
            get {
                return String.Empty;
            }
        }

        public override IEnumerable<string> Names {
            get {
                yield break;
            }
        }

        public override IEnumerable<INodeObject<INodeType>> InheritsFrom {
            get {
                yield break;
            }
        }


        public override IEnumerable<INodeObject<INodeType>> Children {
            get {
                if (_children == null) {
                    var children = new List<INodeObject<INodeType>>();
                    foreach (var result in Results) {
                        children.Add(result);
                    }
                    _children = children;
                }
                return _children;
            }
        }

        #region IRenderNodeObject Members

        public void Render(INodeObject<INodeType> root, System.IO.TextWriter writer) {
            foreach (INodeObject<INodeType> child in Children) {
                if (child is IRenderNodeObject) {
                    (child as IRenderNodeObject).Render(root, writer);
                }
            }
        }

        public string RenderId {
            get { return String.Empty; }
        }

        #endregion

    }
}
